import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, getUserInfo } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(null)

  const setToken = (newToken) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  const setUserInfo = (info) => {
    userInfo.value = info
  }

  const loginAction = async (credentials) => {
    try {
      const { token: newToken } = await login(credentials)
      setToken(newToken)
      await getUserInfoAction()
      return true
    } catch (error) {
      console.error('Login failed:', error)
      return false
    }
  }

  const getUserInfoAction = async () => {
    try {
      const info = await getUserInfo()
      setUserInfo(info)
      return true
    } catch (error) {
      console.error('Get user info failed:', error)
      return false
    }
  }

  const logout = () => {
    token.value = ''
    userInfo.value = null
    localStorage.removeItem('token')
  }

  return {
    token,
    userInfo,
    loginAction,
    getUserInfoAction,
    logout
  }
}) 